package com.star.gc4.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.star.gc4.common.R;
import com.star.gc4.entity.Music;
import com.star.gc4.service.MsongsService;
import com.star.gc4.service.MusicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/music")
@Slf4j
public class musicController {

	@Autowired
	private MusicService musicService;


	@PostMapping("/save")
	public R<String> save1(@RequestBody Music music){
		log.info("{}",music);
		return musicService.save1(music);
	}

	@GetMapping("/get")
	public R<Music> get(@RequestParam Integer songid){
		return musicService.get1(songid);
	}

	@GetMapping("/delete")
	public R<String> delete(String[] list){
		return musicService.delete1(list);
	}

	@GetMapping("/list")
	public R<Page<Music>> list(String keyword,Integer pageSize,Integer currentPage){
		log.info("get list request: {}",keyword);
		return musicService.list1(keyword, pageSize, currentPage);
	}

	@PostMapping("/upload/music")
	public R<String> uploadMusic1(@RequestPart MultipartFile music,Integer songid) throws IOException {
//		Integer songid = 20;
		log.info("get upload message,id: {}",songid);
		try {
			return musicService.uploadMusic1(music,songid);
		}
		catch (Exception e){
			musicService.delete1(new String[]{songid+""});
			return R.success("-1");
		}
	}

	@RequestMapping("/upload/lrc")
	public R<String> uploadLrc(MultipartFile lrc,Integer songid) throws IOException {
		log.info("get upload message,id: {}",songid);
		try {
			return musicService.uploadLrc1(lrc,songid);
		}
		catch (Exception e){
			musicService.delete1(new String[]{songid+""});
			return R.success("-1");
		}
	}

	@GetMapping("/lrc")
	public R<Map> getLrc(String songid) throws IOException {
		try {
			return musicService.Lrc(songid);
		}
		catch (Exception e){
			log.error("ERROR: {}",e.getMessage(),e);
			return R.success(null);
		}

	}

	//歌曲分页查询
	@GetMapping("/page")
	public R<Page<Music>> page(int page,int pageSize,String songname,String singer) {
		//构造分页构造器
		Page<Music> pageInfo = new Page<>(page, pageSize);
		//构造条件构造器
		LambdaQueryWrapper<Music> queryWrapper = new LambdaQueryWrapper<>();
		if (songname != null) {
			queryWrapper.like(Music::getSongname, songname);
		}
		if (singer != null) {
			queryWrapper.like(Music::getSinger, singer);
		}

		queryWrapper.orderByDesc(Music::getView);
		musicService.page(pageInfo, queryWrapper);
		return R.success(pageInfo);
	}

	@GetMapping("/views")
	public R<String> view(String songid){
		return musicService.addView(songid);
	}
}
